package org.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.dao.ExamDao;
import org.example.entity.ClassEntity;
import org.example.entity.ExamEntity;
import org.example.entity.ResultsInfoEntity;
import org.example.dao.ClassDao;
import org.example.dao.ResultsInfoDao;
import org.example.service.ClassResultsInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ClassResultsInfoServiceImpl extends ServiceImpl<ClassDao, ClassEntity>
        implements ClassResultsInfoService {

    @Autowired
    private ResultsInfoDao resultsInfoDao;

    @Autowired
    private ClassDao classDao;

    @Override
    public Float getClassTotalScore(long examId) {
        List<ResultsInfoEntity> results = resultsInfoDao.selectList(
                new QueryWrapper<ResultsInfoEntity>().eq("exam_id", examId));

        // 计算班级的总成绩
        return results.stream()
                .map(ResultsInfoEntity::getScore)
                .reduce(0f, Float::sum);
    }

    @Override
    public Float getClassAverageScore(long examId) {
        List<ResultsInfoEntity> results = resultsInfoDao.selectList(
                new QueryWrapper<ResultsInfoEntity>().eq("exam_id", examId));

        // 计算班级平均成绩
        return results.stream()
                .map(ResultsInfoEntity::getScore)
                .reduce(0f, Float::sum) / results.size();
    }

    @Override
    public Float getClassHighestScore(long examId) {
        List<ResultsInfoEntity> results = resultsInfoDao.selectList(
                new QueryWrapper<ResultsInfoEntity>().eq("exam_id", examId));

        // 获取班级最高成绩
        return results.stream()
                .map(ResultsInfoEntity::getScore)
                .max(Float::compareTo)
                .orElse(0f);
    }

    @Override
    public int getClassPassCount(long examId, Float passingScore) {
        List<ResultsInfoEntity> results = resultsInfoDao.selectList(
                new QueryWrapper<ResultsInfoEntity>().eq("exam_id", examId));

        // 计算班级通过人数
        return (int) results.stream()
                .filter(result -> result.getScore() >= passingScore)
                .count();
    }

    @Override
    public List<ClassEntity> getClassScores(long examId) {
        // 获取班级的成绩数据，这里假设我们通过 examId 查找班级成绩
        return classDao.selectList(new QueryWrapper<ClassEntity>().eq("exam_id", examId));
    }
}
